package com.gx.common.exception;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.gx.dto.base.enums.ResultCodeEnum;
import com.gx.dto.base.result.CommonResult;
import com.gx.dto.base.result.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 集中处理所有异常
 *
 * @author lpj
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.gx")
public class GlobalExceptionControllerAdvice {


    @ExceptionHandler(value = CommonException.class)
    public CommonResult commonException(CommonException e) {
        log.error("异常信息：{}，异常类型：{}", e.getMessage(), e.getClass());
        return Results.buildFailure(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult exception(Exception e) {
        e.printStackTrace();
        log.error("异常信息：{}，异常类型：{}", e.getMessage(), e.getClass());
        return Results.buildFailure(ResultCodeEnum.UNKNOWN_REASON);
    }

    @ExceptionHandler(value = Throwable.class)
    public CommonResult throwableException(Throwable throwable) {
        throwable.printStackTrace();
        log.error("异常信息：{}，异常类型：{}", throwable.getMessage(), throwable.getClass());
        return Results.buildFailure(ResultCodeEnum.UNKNOWN_REASON);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult doMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        //校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> defaultMessage = CollUtil.getFieldValues(fieldErrors, "defaultMessage", String.class);
        String errMsg = StrUtil.join(",", defaultMessage);
        //收集错误
        log.error("参数异常:{}", errMsg);
        return Results.buildFailure(ResultCodeEnum.PARAM_ERROR.getCode(), errMsg);
    }


}
